package BLL;

import javax.swing.*;
import java.io.File;

/**
 * @author 陈显彩
 * @version 2021.0601
 * @since 1.8
 */

/**
 * 文件删除
 */
public class FileDelete {
    /**
     * 删除文件或目录
     * @param filename 文件或目录名称
     * @return 删除是否成功
     */
    public static boolean Delete(String filename){
        File file = new File(filename);
        if(file.exists()){
            if(file.isDirectory())
                return deleteDirectory(filename);
            else
                return deleteFile(filename);
        }
        else{
            JOptionPane.showMessageDialog(null, "删除文件失败：" + filename + "不存在！", "哦豁", JOptionPane.WARNING_MESSAGE);
            return false;
        }
    }
    
    /**
     * 删除文件
     * @param filename 文件名称
     * @return 删除是否成功
     */
    public static boolean deleteFile(String filename){
        File file = new File(filename);
        if(!file.exists() || !file.isFile()){
            JOptionPane.showMessageDialog(null, "删除文件失败：" + filename + "不存在！", "哦豁", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        if(file.delete()){
            JOptionPane.showMessageDialog(null, "删除文件" + filename + "成功！", "好耶", JOptionPane.WARNING_MESSAGE);
            return true;
        }
        else{
            JOptionPane.showMessageDialog(null, "删除文件" + filename + "失败！", "哦豁", JOptionPane.WARNING_MESSAGE);
            return false;
        }
    }
    
    /**
     * 删除目录
     * @param dirname 目录名称
     * @return 删除是否成功
     */
    public static boolean deleteDirectory(String dirname){
        if(!dirname.endsWith(File.separator))
            dirname += File.separator;
        File dir = new File(dirname);
        if(!dir.exists() || !dir.isDirectory()){
            JOptionPane.showMessageDialog(null, "删除目录失败：" + dirname + "不存在！", "哦豁", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        boolean flag = false;
        File[] all_files = dir.listFiles();
        for(File file: all_files){
            if(!Delete(file.getAbsolutePath())){
                flag = true;
                break;
            }
        }
        if(flag){
            JOptionPane.showMessageDialog(null, "删除目录失败！", "哦豁", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        if(dir.delete()){
            JOptionPane.showMessageDialog(null, "删除目录成功！", "好耶", JOptionPane.WARNING_MESSAGE);
            return true;
        }
        else{
            JOptionPane.showMessageDialog(null, "删除目录失败！", "哦豁", JOptionPane.WARNING_MESSAGE);
            return false;
        }
    }
}

